package com.fortune.controller;

import com.fortune.base.BaseAPIExcution;
import com.fortune.base.BaseController;
import com.fortune.dto.excution.ClientUserExcution;
import com.fortune.dto.excution.ProductExcution;
import com.fortune.dto.in.cOrder.PurchaseGiftDto;
import com.fortune.dto.in.clientOrder.*;
import com.fortune.enums.ClientEnum;
import com.fortune.enums.ClientUserEnum;
import com.fortune.enums.ProductEnum;
import com.fortune.exception.db.DeleteInnerErrorException;
import com.fortune.exception.db.InsertInnerErrorException;
import com.fortune.service.ClientUserService;
import com.fortune.util.UUIDUtil;
import com.fortune.vo.cOrder.CorderSubmit;
import com.fortune.vo.clientOrder.Order;
import com.fortune.vo.clientOrder.OrderDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Api(value = "wechat/client/order", description = "客户订单相关", tags = {"微信小程序（业务员）：订单管理"})
@RestController
@RequestMapping("wechat/client/order")
public class ClientOrderController extends BaseController{
	@Autowired
	private ClientUserService clientUserService;
	@ApiOperation(value = "订单列表", nickname = "clientOrderList", notes = "", tags={ "@朱承祚" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@GetMapping(value = "list",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<List<Order>> clientOrderList(ListDto listDto) {
		String mid = getMId();
		String did = getDId();
		List<Order> clientOrderList=clientUserService.clientOrderList(listDto,mid,did);
		if (clientOrderList==null){
			return new ClientUserExcution(clientOrderList, ClientUserEnum.FIND_RESULT_AIR);
		}
		return new ClientUserExcution(clientOrderList, ClientUserEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "添加订单", nickname = "clientOrderAdd", notes = "", tags={ "@朱承祚" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@PostMapping(value = "add",
			produces = { MediaType.APPLICATION_JSON_VALUE },
			consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<CorderSubmit> add(@Validated @RequestBody DOrderSubmitDto addDto) {
		String mid = getMId();
		String did = getDId();
		String userId = getUserId();
		DOrderProductDto products = addDto.getProducts();
		String clientId = products.getClientId();//客户id
		String id = UUIDUtil.get32UUID();//订单id
		String no = UUIDUtil.get32UUID();//订单编号
		String productId = products.getProductId();//商品ID
		//int num = products.getNum();//总商品数量
		List<PurchaseGiftDto> sales = products.getSales();//销售
		List<PurchaseGiftDto> gift = products.getGift();//赠送
		//int backBox = products.getBackBox();//回空箱数量
		BigDecimal pTotalPrice = products.getdTotalPrice();//商品总钱数
		BigDecimal dTotalPrice = products.getdTotalPrice();//押金钱数
		int addCOrder = clientUserService.addDOrder(mid, did, clientId, id, no, userId, pTotalPrice, dTotalPrice);
		if(addCOrder < 0){
			throw new InsertInnerErrorException("添加失败！");
		}
		CorderSubmit corderSubmit = new CorderSubmit();
		corderSubmit.setId(id);
		corderSubmit.setNo(no);

		int a = 0;
		//销售
		for(int j = 0; j < sales.size(); j++){
			PurchaseGiftDto purchaseGiftDto = sales.get(j);
			int detailsNo = a + 1;
			a = detailsNo;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetails = clientUserService.addDOrderDetails(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetails < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		//赠送
		for(int x = 0; x < gift.size(); x++){
			PurchaseGiftDto purchaseGiftDto = gift.get(x);
			int detailsNo = a + 1;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetailsByZS = clientUserService.addDOrderDetailsByZS(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetailsByZS < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		return new ClientUserExcution<CorderSubmit>(corderSubmit, ClientUserEnum.ADD_SUCCESS);
	}
	
	@ApiOperation(value = "获取订单详情", nickname = "clientOrderDetail", notes = "", tags={ "@朱承祚" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "detail",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<OrderDetail> detail(@Validated @NotBlank(message="订单id不能为空") String orderId) {
		OrderDetail detail=clientUserService.clientOrderDetail(orderId);
		return new ClientUserExcution(detail, ClientUserEnum.FIND_SUCCESS);
	}
	
	@ApiOperation(value = "提交订单(修改订单状态为已提交)", nickname = "clientOrderCommit", notes = "", tags={ "@朱承祚" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PutMapping(value = "commit",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> commit(@Validated @NotBlank(message="订单id不能为空") String orderId) {
		int num = clientUserService.updateOrderStatus(orderId);
		if(num > 0){
			return new ClientUserExcution<Void>(null, ClientUserEnum.EDIT_SUCCESS);
		}
		return new ClientUserExcution<Void>(null, ClientUserEnum.EDIT_ERROR);
	}
	
	@ApiOperation(value = "编辑订单", nickname = "clientOrderEdit", notes = "", tags={ "@朱承祚" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PutMapping(value = "edit",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<CorderSubmit> commit(HttpServletRequest request,@Validated @RequestBody DClientOrderEditDto editDto) {
		DOrderProductEditDto products = editDto.getProducts();
		String mid = getMId();
		String did = getDId();
		String ordersId = products.getOrdersId();//订单id
		String orderNums = products.getOrderNum();//订单编号
		String clientId = products.getClientId();//客户id
		int editOrder = clientUserService.editOrder(mid, did, ordersId ,orderNums,clientId);
		if(editOrder < 1){
			throw new DeleteInnerErrorException("删除失败！");
		}
		String userId = "kh123";
		String id = UUIDUtil.get32UUID();//订单id
		String no = UUIDUtil.get32UUID();//订单编号
		String productId = products.getProductId();//商品ID
		//int num = products.getNum();//总商品数量
		List<PurchaseGiftDto> sales = products.getSales();//销售
		List<PurchaseGiftDto> gift = products.getGift();//赠送
		//int backBox = products.getBackBox();//回空箱数量
		BigDecimal pTotalPrice = products.getdTotalPrice();//商品总钱数
		BigDecimal dTotalPrice = products.getdTotalPrice();//押金钱数
		int addCOrder = clientUserService.addDOrder(mid, did, clientId, id, no, userId, pTotalPrice, dTotalPrice);
		if(addCOrder < 0){
			throw new InsertInnerErrorException("添加失败！");
		}
		CorderSubmit corderSubmit = new CorderSubmit();
		corderSubmit.setId(id);
		corderSubmit.setNo(no);

		int a = 0;
		//销售
		for(int j = 0; j < sales.size(); j++){
			PurchaseGiftDto purchaseGiftDto = sales.get(j);
			int detailsNo = a + 1;
			a = detailsNo;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetails = clientUserService.addDOrderDetails(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetails < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		//赠送
		for(int x = 0; x < gift.size(); x++){
			PurchaseGiftDto purchaseGiftDto = gift.get(x);
			int detailsNo = a + 1;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetailsByZS = clientUserService.addDOrderDetailsByZS(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetailsByZS < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		return new ClientUserExcution<CorderSubmit>(corderSubmit,ClientUserEnum.ADD_SUCCESS);
	}
}
